<!--

-->
<template>
    <vxe-modal v-model="visible" :position="{top: '60px'}" :title="title" destroy-on-close height="700"  :min-width="layout.modalMinWidth(800)" resize show-footer show-maximize :width="layout.modalWidth(800)" :height="layout.modalHeight()" @close="cancelClick">
        <PermissionTree v-loading="state.isLoading||isSubmitting" :list="state.tree"/>
        <template #footer>
            <el-button @click="cancelClick">取消</el-button>
            <el-button :loading="isSubmitting" type="primary" @click="beforeSubmit">
                确定
            </el-button>
        </template>
    </vxe-modal>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from "vue";
import {FormMixins} from "@/utils/FormMixins";
import PermissionTree from "./components/PermissionTree.vue"
import * as api from "./api.js"

const {ELForm, visible, title, layout, isLoading, isSubmitting, state, setOptions, submitSuccess, cancelClick} = FormMixins();
const {$message} = window;

const Model = () => {
    return {
        id: null,
        name: null,
        sort: 0,
        remark: null,
    }
}
// 校验规则
const rules = computed(() => {
    return {}
})

// 表单显示
async function show(config) {
    setOptions(config);
    state.model = Model();
    state.model = {...state.model, ...state.options}
    state.isLoading = true
    state.checkedMenus = [];
    // 初始化数据
    // 查询数据
    api.getRoleMenuPermission({roleId: state.options.id}).then(({success, data}) => {
        state.isLoading = false
        if (success) {
            state.tree = data;
            console.primary("菜单权限树", data)
        }
    })
}

// 校验表单
function beforeSubmit() {
    // 在这里 tree 中提取数据
    isSubmitting.value = true
    const checkedMenus = [];
    state.tree.treeMap(item => {
        if (item.hasPerm) {
            checkedMenus.push({sysRoleId: state.options.id, sysMenuId: item.id, menuName: item.name, dataScopeType: item.dataScopeType})
        }
    }, 'children')

    setTimeout(() => {
        state.checkedMenus = checkedMenus;
        submit()
    }, 1000)
}


// 提交表单
async function submit() {
    isSubmitting.value = true
    console.log("submit: ", state.model)
    // const body = [...state.checkedMenus] // 有数据权限版本
    const body = {
        roleId: state.options.id,
        menuIds: state.checkedMenus.map(item => item.sysMenuId),
    } // 无数据权限版本
    const {success, data} = await api.UpdateRolePermissions(body);
    isSubmitting.value = false
    if (!success) return 0;
    $message.success("操作成功")
    submitSuccess()
}

onMounted(() => {
})
defineExpose({
    show
})
</script>


<style lang="scss" scoped>
.PermissionForm {
}
</style>
